package com.beney.util.db;

import com.beney.common.StorageInfo;

import java.io.*;

/**
 * 写入文件工具
 *
 * @author Beney
 */
public class FileOutUtil {
    private FileOutUtil() {
    }

    /**
     * 将用户生成的题目写入用户的文件夹
     *
     * @param userName 用户名
     * @return 文件的保存地址；null-失败
     */
    public static String saveQuesToUserFolder(String userName, StringBuilder[] ques) {
        File dir = new File(StorageInfo.PAPERS_DIR + '/' + userName);
        if (!dir.exists()) {
            System.out.println("error：用户文件夹不存在");
            return null;
        }
        File file = new File(StorageInfo.PAPERS_DIR +
                '/' + userName + '/' +
                StorageInfo.CreatePaperName());
        return saveQuesToUserFile(file, ques);
    }

    private static String saveQuesToUserFile(File file, StringBuilder[] ques) {
        int len = ques.length;
        StringBuilder q;
        try {
            if (!file.exists())
                file.createNewFile();
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file)));
            for (int i = 0; i < len; ++i) {
                q = ques[i].insert(0, StorageInfo.GetQuestionId(i + 1));
                bw.write(q.toString());
                bw.write("\r\n");
                bw.write("\r\n");
            }
            bw.flush();
            bw.close();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return file.getAbsolutePath();
    }
}
